#include "musiclist.h"
#include "music.h"
#include<QVector>
#include<QDebug>
#include <QSqlQuery>
#include <QSqlError>
MusicList::MusicList()
{

}
void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    for(auto musicUrl : urls)
    {
        // 由于添加进来的⽂件不⼀定是歌曲⽂件，因此需要再次筛选出⾳乐⽂件

        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForFile(musicUrl.toLocalFile());
        QString mimetype = mime.name();
        qDebug()<<mimetype;
        if(mime.name() != "audio/mpeg" && mime.name() != "audio/flac")
        {
            continue;
        }
        // 如果是⾳乐⽂件，加⼊歌曲列表
        qDebug()<<"new music URL:"<<musicUrl;
        Music music(musicUrl);
        musicList.push_back(music);
    }
}

MusicList::iterator MusicList::findMusicById(const QString &musicId)
{
    for(iterator it = begin(); it != end(); ++it)
    {
        if(it->getMusicId() == musicId)
        {
            return it;
        }
    }
    return end();
}

MusicList::iterator MusicList::begin()
{
    return musicList.begin();
}

MusicList::iterator MusicList::end()
{
    return musicList.end();
}

bool MusicList::empty() const
{
    musicList.isEmpty();
}

void MusicList::writeToDB()
{
    for(auto music : musicList)
     {
        music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, musicSinger, albumName, \
                    duration, musicUrl, isLike, isHistory \
                    FROM musicInfo");

        QSqlQuery query;
        if(!query.exec(sql))
        {
            qDebug()<<"数据库查询失败";
            return;
        }

        while(query.next())
        {
            Music music;
            music.setMusicId(query.value(0).toString());
            music.setMusicName(query.value(1).toString());
            music.setSingerName(query.value(2).toString());
            music.setAlbumName(query.value(3).toString());
            music.setDuration(query.value(4).toLongLong());
            music.setMusicUrl(query.value(5).toString());
            music.setIsLike(query.value(6).toBool());
            music.setIsHistory(query.value(7).toBool());

            musicList.push_back(music);
        }
}
